<script
  setup
  lang="ts"
>
import type { Banner } from './ListNavs.vue'
import { useResizeObserver } from '@vueuse/core'

const props = defineProps({
  list: {
    type: Array as PropType<Banner[]>,
    default: () => [],
  },
  titleCol: {
    type: String,
    default: 'title_name',
  },
  imgCol: {
    type: String,
    default: 'cover_file_name',
  },
  autoplay: {
    type: Boolean,
    default: true,
  },
  duration: {
    type: Number,
    default: 3000,
  },
})

const bannerList = computed(() => {
  const result: Banner[] = []
  if (props.list.length) {
    props.list.forEach((item) => {
      // if (item.uid?.lastIndexOf('_') !== item?.uid?.length - 2) {
      result.push(item)
      // }
    })
  }
  return result
})
const swiperListRef = ref<HTMLElement | null>(null)
const swiperListWrapRef = ref<HTMLElement | null>(null)
const current = ref(0)
let timer: any = null

function playSwiper() {
  clearInterval(timer)
  timer = setInterval(() => {
    next()
  }, props.duration)
}

function initSwiperEvent() {
  clearInterval(timer)
  if (props.autoplay && swiperListWrapRef.value) {
    playSwiper()
    swiperListWrapRef.value.addEventListener('mouseenter', () => {
      clearInterval(timer)
    })
    swiperListWrapRef.value.addEventListener('mouseleave', () => {
      playSwiper()
    })
  }
}

onMounted(() => {
  // 使用resize observer监听轮播图的宽度变化
  initSwiperEvent()
  useResizeObserver(swiperListWrapRef, (entries) => {
    if (swiperListRef.value) {
      swiperListRef.value.scrollLeft = current.value * swiperListRef.value.offsetWidth / 2
    }
  })
})
onUnmounted(() => {
  clearInterval(timer)
})

function prev() {
  if (!swiperListRef.value)
    return
  current.value--
  if (current.value <= 0) {
    current.value = bannerList.value.length - 2
  }
  swiperListRef.value.scrollLeft = current.value * swiperListRef.value.offsetWidth / 2

  // swiperListRef.value.scrollLeft -= swiperListRef.value.offsetWidth / 2
  // if (swiperListRef.value.scrollLeft <= 0) {
  //   swiperListRef.value.scrollLeft = swiperListRef.value.scrollWidth - swiperListRef.value.offsetWidth
  // }
}

function next() {
  if (!swiperListRef.value)
    return
  current.value++
  if (current.value >= bannerList.value.length - 2) {
    current.value = 0
  }
  swiperListRef.value.scrollLeft = current.value * swiperListRef.value.offsetWidth / 2
  // swiperListRef.value.scrollLeft += swiperListRef.value.offsetWidth / 2
  // if (swiperListRef.value.scrollLeft >= (swiperListRef.value.scrollWidth - swiperListRef.value.offsetWidth)) {
  //   swiperListRef.value.scrollLeft = 0
  // }
}

function getLinkUrl(item) {
  let url = ''
  const category = item.category || item.classify_name || ''

  if (category.split('/')[0] === '健康陕西') {
    url = `/peopleHealth/healthyShaanxiDetail?id=${item.id}`
  }
  else if (category === '头条资讯') {
    url = `/peopleHealth/topNewsDetail?id=${item.id}`
  }
  else if (category.split('/')[0] === '百姓健康系列栏目') {
    url = `/peopleHealth/peopleHealthSeriesDetail/${item.id}?type=${item.classify_name.split('/')[1]}&ptUid=${item.pt_uid}`
  }
  else if (category.split('/')[0] === '健康知识') {
    url = `/peopleHealth/knowledgeDetail/${item.id}&1`
  }
  else if (category.split('/')[0] === '科普资料') {
    url = `/peopleHealth/popularizationDetail/${item.id}&${item.classify_name.split('/')[1]}`
  }
  else if (category.split('/')[0] === '宣传活动') {
    url = `/peopleHealth/HealthActivityDetail/${item.id}&${item.classify_name.split('/')[1]}`
  }
  else if (category?.indexOf('中医科普资料') === 0 && item?.id) {
    url = `/peopleHealth/outKnowledgeDetail/${item.id}&中医健康科普详情`
  }
  return url
}
</script>

<template>
  <div ref="swiperListWrapRef" class="motion-blur swiper-list-wrap h-full w-full">
    <div class="prev" @click="prev">
      <i class="i-fa-solid-chevron-circle-left" />
    </div>
    <div class="next" @click="next">
      <i class="i-fa-solid-chevron-circle-right" />
    </div>
    <div ref="swiperListRef" class="motion-blur swiper-list h-full w-full">
      <NuxtLink
        v-for="item in bannerList" :key="item.id" :to="getLinkUrl(item)" target="_blank"
        class="swiper-item pos-relative"
      >
        <el-image class="h-full max-h-400px w-full" :src="getImgUrl(item[imgCol])" fit="cover" />
        <p class="absolute bottom-0 left-0 right-0 truncate bg-#000/45 px-20px py-5px text-#fff" hover="text-#ccc">
          {{ item[titleCol] }}
        </p>
      </NuxtLink>
    </div>
  </div>
</template>

<style
  scoped
  lang="scss"
>
.swiper-list-wrap {
  position: relative;

  &:hover {
    .prev,
    .next {
      opacity: 0.8;
    }
  }

  .prev,
  .next {
    position: absolute;
    top: 50%;
    left: 10px;
    transform: translateY(-50%);
    z-index: 1;
    cursor: pointer;
    color: #f1f1f1;
    font-size: 30px;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    opacity: 0.1;

    &:hover {
      color: #999;
    }
  }

  .next {
    right: 10px;
    left: auto;
  }
}

.swiper-list {
  display: flex;
  overflow-x: auto;
  overflow-y: hidden;
  scroll-behavior: smooth;

  /*定义滚动条样式（高宽及背景）*/
  &::-webkit-scrollbar {
    width: 6px;
    /* 滚动条宽度， width：对应竖滚动条的宽度  height：对应横滚动条的高度*/
    height: 4px;
    background: #f1f1f1;
  }

  /*定义滚动条轨道（凹槽）样式*/
  &::-webkit-scrollbar-track {
    -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
    /* 较少使用 */
    border-radius: 3px;
    background: rgba(0, 0, 0, 0.1);
  }

  /*定义滑块 样式*/
  &::-webkit-scrollbar-thumb {
    border-radius: 3px;
    height: 100px;
    /* 滚动条滑块长度 */
    background: rgba(0, 0, 0, 0.2);
  }

  .swiper-item {
    min-width: 50%;
    display: inline-block;
  }
}
</style>
